<?php

/* If no headers was sent: main call */
if (!headers_sent())
{
    $excel = True;

    require('database.php');
    require('auth.php');
    require('core.php');

    // Verifica se esta autenticado com pelo menos nivel 3
    validaPermissao(3);

    // Define file type
    header("Content-type: application/vnd.ms-excel");

    // Define file name and to be downloaded
    header("Content-Disposition: attachment; filename=\"Employees.xls\"");
    
}

// Determina periodo de tempo
$from = (@$_GET['from']? strtotime($_GET['from']) : inicio_ultima_quinzena());
$to = (@$_GET['to']? strtotime($_GET['to']) : fim_ultima_quinzena());

if ($to)
	$to = min($to, $_SERVER['REQUEST_TIME']);

$resultado = query_bd("SELECT *, employees.id as emplid FROM employees, contacts WHERE " .
	"ISNULL(leaved) AND employees.contact_id=contacts.id " .
	(isset($_GET['search'])? "AND contacts.name LIKE '%{$_GET['search']}%'" : "") .
	" ORDER BY contacts.name");

// Mostra uma tabela com todos os funcionarios e alguns dados
echo "<table id=employees>";

if (!isset($excel))
    echo "<caption><em>", mysql_affected_rows(), " Active employees, with data analisys",
    ($from? " from " . date("M j Y", $from) : ""),
    ($to? " until " . date("M j Y", $to) : ""),
    (@$_GET['location']? " subjected to location {$location_name}" : ""),
    "</em></caption><tr>";

echo ((isset($_GET['print']) || isset($excel))? "" : "<th>"),
"<th>Name<th>Contact<th>Driver expiration<th>Labor<th>Labor expense(+tip)";

$TOTAL_LABOR = 0;
$TOTAL_LABOR_EXP = 0.0;

while ($employee = mysql_fetch_array($resultado))
{
	flush();	/* Manda o que ja tem em buffer para o cliente */

	echo "<tr>";

	if (!isset($_GET['print']) && !isset($excel))
	{
		echo "<td><a href='employee.php?id={$employee['emplid']}'>",
            "<img class=employee_picture src='",
            ($employee['has_picture']? "portrails/{$employee['emplid']}_thumb.jpg" : "portrails/unknown_thumb.png"),
            "' alt=''></a>";
	}

	echo "<td><a href='"  . dirname($_SERVER['HTTP_REFERER']) . "/employee.php?id={$employee['emplid']}'>",
         $employee['name'] . "</a>";
	echo "<td>{$employee['number']} {$employee['street']} {$employee['complement']}<br>",
		"{$employee['city']} {$employee['state']} {$employee['zipcode']}<br>",
		"{$employee['phone']} {$employee['cellphone']}<br>{$employee['email']}";
    echo "<td>", date("M j Y", strtotime($employee['driverexp']));

	// Busca por todos os time cards com as horas do funcionario e soma labor e labor expense
	$employee_info = query_bd("SELECT TIME_TO_SEC(clocks.labor) AS seclabor, " .
	"clocks.labor, clocks.labor_expense, reports.valet_payrate, reports.manager_payrate FROM clocks, reports WHERE " .
	"clocks.report_id=reports.id AND clocks.employee_id={$employee['emplid']} AND reports.state = ". ACCEPTED .
	($from? " AND UNIX_TIMESTAMP(reports.reportdate) >= {$from}" : "") .
	($to? " AND UNIX_TIMESTAMP(reports.reportdate) <= {$to}" : "") .
	(@$_GET['location']? " AND reports.special_event = False AND reports.location_event_id = " . @$_GET['location'] : "") );
	$LABOR = 0;
	$LABOR_EXP = 0.0;
	while ($clock = mysql_fetch_array($employee_info))
	{
		// Soma labor
		$LABOR += $clock['seclabor'];

		// Soma pagamento
		$LABOR_EXP += $clock['labor_expense'];

		unset($clock);
	}
	unset($employee_info);

	//Mostra
	echo "<td>", toTime($LABOR);
	echo "<td>", show_money(-$LABOR_EXP);

	//Soma totais
	$TOTAL_LABOR += $LABOR;
	$TOTAL_LABOR_EXP += $LABOR_EXP;

	unset($employee);
}
unset($resultado);

// Conclusoes gerais
echo "<tr>", ((isset($_GET['print']) || isset($excel))? "" : "<th>"), "<th><th><th><th>",
	toTime($TOTAL_LABOR), "<th>",
	show_money(-$TOTAL_LABOR_EXP);
echo "</table>";

?>
